package cn.lhl.config;

import cn.lhl.sys.entity.SysUser;
import cn.lhl.sys.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConf2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
	@Autowired
	private SysUserMapper sysUserMapper;





    /**
     * 读数据库
     */

	@Override
	protected UserDetailsService userDetailsService() {
		return username -> {
			if (username == null || username.trim().length() <= 0) {
				throw new UsernameNotFoundException("用户名为空");
			}

			SysUser sysUser = sysUserMapper.selectByidWithAuthority(username);
			if (sysUser != null) {
				return sysUser;
			}
			throw new UsernameNotFoundException("用户不存在!");
		};
	}

    /**
     * 权限处理
     *
     * @param http
     * @throws Exception
     */
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭csrf
        http.csrf().disable();

        //   permitAll();放过的url
		// 登录的配置
        http.formLogin().usernameParameter("id");//自定义的username的映射字段名
        http.formLogin().passwordParameter("password");//自定义的password的映射字段名
        // 配置登录页面 设置自定义的登录页
        http.formLogin().loginPage("/login").successForwardUrl("/home.html").permitAll();
        // 配置登录成功后的操作
        //http.formLogin().successHandler(new LoginSuccessHandler());

        //配置无权限403的页面路径
        http.exceptionHandling().accessDeniedPage("/auth/limit.html");
        // 用户权限不足处理器
        //http.exceptionHandling().accessDeniedHandler(new AuthLimitHandler());

        // 登出授权  退出的配置 logoutSuccessUrl退出完成要去的页面
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").permitAll();


        // 授权配置
        http.authorizeRequests()
                /* 所有静态文件可以访问 */
                .antMatchers("/js/**","/css/**","/images/**").permitAll()
                /* 所有 以/ad 开头的 广告页面可以访问 */
                .antMatchers("/ad/**").permitAll()
                //设置可以直接访问的路径
                .antMatchers("/hello","/test").permitAll()

                /* 动态url权限 */
                //.withObjectPostProcessor(new DefinedObjectPostProcessor())
                /* url决策 */
                //.accessDecisionManager(accessDecisionManager())

                .anyRequest().authenticated();

    }


    /**
     * 放行规则  放行 不会走security过滤连
     *
     * @param web
     * @throws Exception
     */
    public void configure(WebSecurity web) throws Exception {
        //设置忽略的url
        web.ignoring().antMatchers("/hello");
        web.ignoring().antMatchers("/css/**", "/js/**");

    }

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder);
	}

    /**
     * 密码加密类
     *
     * @return
     */

    @Bean
    public PasswordEncoder passwordEncoder() {
        //不加密的
        return NoOpPasswordEncoder.getInstance();
        //return new BCryptPasswordEncoder();
    }


}
